package com.b510.test.iqiyi;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.b510.bean.Person;
import com.b510.service.PersonService;
import com.svo.util.HttpUtils;

import us.codecraft.xsoup.Xsoup;

public class IqiyiZongyi {
    private static PersonService personService;
	private Person person;
	public static void main(String[] args) {
        ApplicationContext act = new ClassPathXmlApplicationContext("bean.xml");
        personService = (PersonService) act.getBean("personService");
        new IqiyiZongyi().start();
    }
    public void start() {
        int totalPage = 2;
        String listUrl = "https://pcw-api.iqiyi.com/search/recommend/list?channel_id=6&data_type=1&mode=11&page_id=1&ret_num=48";
        for (int i = 1; i <= totalPage; i++) {
        	System.err.println("page:"+i);
            try {
                String reqUrl = listUrl.replace("page_id=1","page_id="+i);
                String json = HttpUtils.get(reqUrl,"");
                JSONObject jo = new JSONObject(json).optJSONObject("data");
                JSONArray array = jo.optJSONArray("list");
                if (array == null) {
                    if (jo.optInt("has_next") == 0) {
                        System.err.println("page over");
                        break;
                    }
                    Thread.sleep(4000);
                    i--;
                    continue;
                }
                for (int j = 0; j < array.length(); j++) {
                    JSONObject listItem = array.getJSONObject(j);
                    String playUrl = listItem.getString("playUrl");
                    person = new Person();
                    person.setVod_cid(listItem.optString("channelId"));
                    person.setVod_series(listItem.optString("albumId"));
                    person.setVod_name(listItem.optString("albumName"));
                    int videoCount = listItem.getInt("videoCount");
                    String actor = getActor(listItem);
                    person.setVideoCount(videoCount);
                    person.setVod_actor(actor);
                    String imageSize = listItem.optJSONArray("imageSize").toString().replace("[", "").replace("]", "").replace("\"", "");
                    person.setImageSize(imageSize);
                    getFirstInfo(playUrl);
//                    break;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            break;
        }
    }

    private void getFirstInfo(String playUrl) {
        try {
            Document doc = Jsoup.parse(new URL(playUrl), 30*1000);
            String pageInfo = Xsoup.select(doc, "//div[@is='i71-play-ab']/@:page-info").get();
            String videoInfo = Xsoup.select(doc, "//div[@is='i71-play-ab']/@:video-info").get();
            JSONObject videoInfoJo = new JSONObject(videoInfo);
			JSONArray category = videoInfoJo.optJSONArray("categories");
            Map<String, String> map = getInfo(category);
            String type = map.get("类型");
            String area = map.get("地区");
            String language = map.get("语种");
            
            person.setVod_area(area);
            person.setVod_language(language);
            person.setVod_type(type);
//            person.setVod_director(getDirector(item));
            
            System.out.println("title size:"+pageInfo);
            JSONObject jo = new JSONObject(pageInfo);
            String albumUrl = jo.optString("albumUrl");
            albumUrl = getAbsUrl(albumUrl);
            getAllPage(albumUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getAllPage(String albumUrl) {
        try {
            System.out.println("albumUrl:"+albumUrl);
            Document doc = Jsoup.parse(new URL(albumUrl), 30*1000);
            List<String> links = Xsoup.select(doc, "//ul[@id='albumpic-showall-wrap']/li/div[1]/a/@href").list();
            List<String> titles = Xsoup.select(doc, "//ul[@id='albumpic-showall-wrap']/li/div[1]/a/img/@alt").list();
            List<String> imgs = Xsoup.select(doc, "//ul[@id='albumpic-showall-wrap']/li/div[1]/a/img/@src").list();
            if (links == null || links.size() == 0) {
            	String html = HttpUtils.get(albumUrl, "");
            	Pattern pattern = Pattern.compile(".+list: (.+?)\\}\\);.+");
                Matcher matcher = pattern.matcher(html);
                if (matcher.find()) {
    				String rsStr = matcher.group(1).trim();
    				String json = rsStr.split("\\|\\|")[0].trim();
    	            JSONArray array = new JSONArray(json);
    	            for (int i = 0; i < array.length(); i++) {
    	            	JSONObject item = array.getJSONObject(i);
    	            	String tvId = item.optString("tvId");
    	            	String playUrl = item.getString("url");
    	            	String albumId = item.optString("albumId");
    	            	String shortTitle = item.optString("shortTitle");
    	            	String desc = item.optString("description");
    	            	
    	            	String thumb = item.optString("imageUrl");
    	                String duration = item.optString("duration");
    	                
    	                String filmTime = item.optString("period");
    	                String focus = item.optString("focus");
    	                person.setVod_title(focus);
    	                
    	                person.setVod_pic(thumb);
    	                int seconds = SpringJDBCTest.getDuration(duration);
    	                person.setVod_length(seconds);
    	                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    	    			long date = sdf.parse(filmTime).getTime();
    	                person.setFilmtime(new java.sql.Date(date));
    	                person.setVod_year(filmTime.substring(0,4));
    	                
    	            	person.setVod_content(desc);
    	            	person.setVod_id(tvId);
    	            	person.setVod_series(albumId);
    	            	person.setVod_title(shortTitle);
    	            	person.setVod_reurl(playUrl);
    	            	personService.save(person);
    	            }
    			}else {
    				System.err.println("not find");
    			}
			}else {
				for (int i = 0; i < links.size(); i++) {
	            	person.setVod_title(titles.get(i));
	            	person.setVod_reurl(links.get(i));
	            	person.setVod_pic(imgs.get(i));
	            	personService.save(person);
				}
			}
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static String getDirector(JSONObject item) {
		JSONArray directorArr = item.optJSONObject("people").optJSONArray("director");
		StringBuilder director = new StringBuilder();
		if (directorArr != null) {
			for (int i = 0; i < directorArr.length(); i++) {
				String name = directorArr.getJSONObject(i).getString("name");
				if (director.length() == 0) {
					director.append(name);
				}else {
					director.append(","+name);
				}
			}
		}
		return director.toString();
	}
    private static String getActor(JSONObject item) {
		StringBuilder actorSb = new StringBuilder();
		JSONArray actorArr = item.optJSONObject("people").optJSONArray("host");
		if (actorArr != null) {
			for (int j = 0; j < actorArr.length(); j++) {
				String actorName = actorArr.getJSONObject(j).getString("name");
				if (j == 0) {
					actorSb.append(actorName);
				}else {
					actorSb.append(","+actorName);
				}
			}
		}
		return actorSb.toString();
	}
    private String getAbsUrl(String url){
        if (url.startsWith("//")){
            url = "https:"+url;
        }
        return url;
    }
    private static Map<String, String> getInfo(JSONArray category) {
		Map<String, String> map = new HashMap<>();
		JSONArray categories = category;
		if (categories != null) {
			for (int i = 0; i < categories.length(); i++) {
				JSONObject jo = categories.getJSONObject(i);
				String subName = jo.optString("subName");
				String name = jo.optString("name");
				if (map.get(subName) != null) {
					map.put(subName, map.get(subName)+","+name);
				}else {
					map.put(subName, name);
				}
			}
		}
		return map;
	}
    
}